﻿using System;
//the following TFS server references can be found under %Program Files%\Microsoft Team Foundation Server 2010\Application Tier\TFSJobAgent
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Server;
using Microsoft.TeamFoundation.VersionControl.Common;

namespace DscpMed.TFSSubscribers
{
    public class BranchSecurityInheritOnly : ISubscriber
    {
        public string Name
        {
            get { return "BranchSecurityInheritOnly"; }
        }

        public SubscriberPriority Priority
        {
            get { return SubscriberPriority.Normal; }
        }

        //When debuging, copy .dlls and .pdb 
        //to %Program Files%\Microsoft Team Foundation Server 11.0\Application Tier\Web Services\bin\Plugins
        public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext,
            NotificationType notificationType,
            object notificationEventArgs,
            out int statusCode,
            out string statusMessage,
            out ExceptionPropertyCollection properties)
        {
            EventNotificationStatus response = EventNotificationStatus.ActionApproved;
            properties = new ExceptionPropertyCollection();
            statusMessage = String.Empty;
            statusCode = 0;

            // If this is a Check-in notification and is a decision point
            if (notificationEventArgs is CheckinNotification && notificationType == NotificationType.Notification)
            {
                CheckinNotification args = notificationEventArgs as CheckinNotification;
                if (args.CheckinType == CheckinType.Branch)
                {
                    var securityService = requestContext.GetService<TeamFoundationSecurityService>();
                    var vcSecurity = securityService.GetSecurityNamespace(requestContext, SecurityConstants.RepositorySecurityNamespaceGuid);
                    vcSecurity.RemoveAccessControlLists(requestContext, args.GetSubmittedItems(requestContext), true);
                }
            }
            return response;
        }

        public Type[] SubscribedTypes()
        {
            return new Type[] { typeof(CheckinNotification) };
        }
    }
}
